<template>
	<div>
		<InputBox @dragFile="dragFile">
			<el-button class="upload-btn" size="small" @click="getFile"
				>选择或拖入文件</el-button
			>
			<span v-if="file" style="margin-left: 10px">{{ file.name }}</span>
			<input
				ref="input"
				type="file"
				style="visibility: hidden; width: 0px; height: 0px"
				@change="fileChange"
			/>
		</InputBox>
		<br />
		<FileSize :file="file"></FileSize>
		<br />
		<UploadBtn :file="file" @upload="upload" @reset="reset"></UploadBtn>
		<br />
		<div v-if="filename">已上传文件名：{{ filename }}</div>
		<Progress :percentage="percentage"></Progress>
	</div>
</template>

<script>
import InputBox from '../components/InputBox'
import FileSize from '../components/FileSize'
import UploadBtn from '../components/UploadBtn'
import Progress from '../components/Progress'
import { baseUrl } from '@/utils/setting'
import { fileSize } from '@/utils'
import './index.scss'
export default {
	components: {
		InputBox,
		FileSize,
		UploadBtn,
		Progress
	},
	data() {
		return {
			file: null,
			filename: null,
			percentage: 0,
			highlight: '',
		}
	},
	computed: {
		showSize() {
			return fileSize(this.file.size)
		},
	},
	methods: {
		dragFile(file) {
			this.file = file
			this.percentage = 0
		},
		getFile() {
			this.$refs.input.dispatchEvent(new MouseEvent('click'))
		},
		fileChange(e) {
			if (e.target.files && e.target.files[0]) {
				this.file = e.target.files[0]
				this.percentage = 0
			}
		},
		reset() {
			this.file = null
			this.filename = null
			this.percentage = 0
			this.highlight = ''
		},
		upload() {
			if (!this.file) {
				this.$message.error('请先选择文件')
				return
			}
			this.percentage = 0
			let form = new FormData()
			form.append('file', this.file)
			this.$axios.post(baseUrl+'/files/upload', form, {
				headers: {
					'Content-Type': 'multipart/form-data',
				},
				onUploadProgress: (progressEvent) => {
					this.percentage = Number(
						((progressEvent.loaded / progressEvent.total) * 100).toFixed(1)
					)
				},
			}).then(res => {
				if(res.data.code === '0') {
					this.$message.success(res.data.desc)
					this.filename = res.data.filename
				} else {
					this.$message.error('上传失败')
				}
			}).catch(error => {
				this.$message.error(error)
			})
		}
	}
}
</script>

<style lang="scss" scoped>
</style>